import { _decorator, Component, instantiate, Node, NodePool, Pool, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PoolManager')
export class PoolManager {
    private static _instance: PoolManager;

    static get instance() {
        if (!this._instance) {
            this._instance = new PoolManager();
        }
        return this._instance;
    }

    private _nodePools: Record<string, NodePool> = {};


    get(obj: Prefab) {
        if (!obj) return;

        const key = obj.name;

        let target: Node;
        let pool = this._nodePools[key];
        if (!pool) {
            target = instantiate(obj);
            pool = new NodePool();
            this._nodePools[key] = pool;
        } else {
            if (pool.size() > 0) {
                target = pool.get();
            } else {
                target = instantiate(obj);
            }
        }
        return target;

    }

    put(obj: Node) {
        if (!obj) return
        const key = obj.name;
        let pool = this._nodePools[key];
        if (!pool) {
            pool = new NodePool();
            this._nodePools[key] = pool;
        } else {
            pool.put(obj);
        }
    }

}


